# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net/
#
use strict; use warnings;

package CCNCore::Provision::JiftyDatabase;
use base qw(CCNCore::Provision::Database);

use CCN::Text;    
use CCNCore::Home;

sub model_name { return shift->jifty_env()->{APPNAME} }

sub update_schema($)
{
    my $self = shift;
    my $c    = shift;

    my @DB_NAMES = $self->get_db_names();
    return unless @DB_NAMES;

    for my $DB_NAME (@DB_NAMES)
    {
        CCN::sql_copy::Jifty::initialize_mysql($DB_NAME,$self->jifty_env);
        
        $self->database_done($DB_NAME);
    }
}

sub bootstrap($)
{
    my $self = shift;
    my $c    = shift;

    $self->update_schema($c);
}

use CCN::sql_copy::CCN;

sub initialize_sqlite3_dump()
{
    my $self = shift;

    CCN::sql_copy::Jifty::initialize_sqlite3($self->dump_file(),$self->jifty_env);
    return CCN::sql_copy::local_sqlite3($self->dump_file());   
}

# Dump the live database into a sqlite3 copy.
sub dump($)
{
    my $self = shift;
    my $db_name = shift;

    $self->log(ref($self)."::dump($db_name)\n");

    my $db_from = CCN::sql_copy::local_mysql($db_name);
    my $db_to = $self->initialize_sqlite3_dump();

    $self->log(ref($self)."::dump($db_name): copy\n");
    return CCN::sql_copy::Jifty::copy($db_from,$db_to,$self->jifty_env);
}

# Populate the live database back from the sqlite3 copy.
sub undump($)
{
    my $self = shift;
    my $db_name = shift;

    $self->log(ref($self)."::undump($db_name)\n");

    my $db_from = CCN::sql_copy::local_sqlite3($self->dump_file());
    $self->log(ref($self)."::undump($db_name): initialize\n");
    my $db_to   = CCN::sql_copy::local_mysql($db_name);
    $self->log(ref($self)."::undump($db_name): copy\n");
    return CCN::sql_copy::Jifty::copy($db_from,$db_to,$self->jifty_env);
}

# Recreate the table layout then populate the live database back from the sqlite3 copy.
# Used in startup_mysql::restore_dbs.
sub reprovision($)
{
    my $self = shift;
    my $db_name = shift;

    $self->log(ref($self)."::reprovision($db_name)\n");

    CCN::sql_copy::Jifty::initialize_mysql($db_name,$self->jifty_env);
    $self->undump($db_name) if -e $self->dump_file();
    $self->database_done($db_name);
}

1;